package com.huifanedu.approval.listener;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huifanedu.approval.constant.FlowableConstant;
import com.huifanedu.approval.entity.ApprovalFormData;
import com.huifanedu.approval.entity.ApprovalInfo;
import com.huifanedu.approval.notify.MessageProduct;
import com.huifanedu.approval.notify.model.ProcessCompleteRecord;
import com.huifanedu.approval.service.ApprovalFlowTaskcfgService;
import com.huifanedu.approval.service.ApprovalFormDataService;
import com.huifanedu.approval.service.ApprovalInfoService;
import com.huifanedu.approval.service.FlowableTaskService;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * <b>功能名：</b>流程执行完监听<br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2020 HUIFANEDU CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2021-3-10 jiabingbing
 */
public class ProcessCompletedListener implements FlowableEventListener {

    private static final Logger log = LoggerFactory.getLogger(ProcessCompletedListener.class);

    @Autowired
    @Lazy
    private ApprovalFlowTaskcfgService approvalFlowTaskcfgService;
    @Autowired
    @Lazy
    private RuntimeService runtimeService;
    @Autowired
    @Lazy
    private FlowableTaskService flowableTaskService;

    @Autowired
    @Lazy
    private ApprovalFormDataService approvalFormDataService;
    @Autowired
    @Lazy
    private ApprovalInfoService approvalInfoService;
    @Autowired
    private MessageProduct messageProduct;

    @Override
    public void onEvent(FlowableEvent event) {
        ExecutionEntityImpl taskEntity = (ExecutionEntityImpl) ((FlowableEntityEventImpl) event).getEntity();
        String processStatus = runtimeService.getVariable(taskEntity.getProcessInstanceId(), FlowableConstant.PROCESS_VARIABLE_STATUS, String.class);
        if (FlowableConstant.PROCESS_STATUS_DONE.equals(processStatus)) {
            //执行完成
        } else if (FlowableConstant.PROCESS_STATUS_DOING.equals(processStatus)) {
            //执行中
            runtimeService.setVariable(taskEntity.getProcessInstanceId(), FlowableConstant.PROCESS_VARIABLE_STATUS, "2");
        } else if (FlowableConstant.PROCESS_STATUS_REJECT.equals(processStatus)) {
            //审核驳回
        }
        //任务执行
        String processStatus1 = runtimeService.getVariable(taskEntity.getProcessInstanceId(), FlowableConstant.PROCESS_VARIABLE_STATUS, String.class);

        try {
            String formDataId = runtimeService.getVariable(taskEntity.getProcessInstanceId(), FlowableConstant.BUSINESS_KEY, String.class);
            ApprovalFormData formData = approvalFormDataService.getOne(Wrappers.<ApprovalFormData>lambdaQuery()
                    .eq(ApprovalFormData::getAfdId, formDataId));
            if (formData != null) {
                ProcessCompleteRecord record = new ProcessCompleteRecord();
                ApprovalInfo approvalInfo = approvalInfoService.getOne(Wrappers.<ApprovalInfo>lambdaQuery()
                        .eq(ApprovalInfo::getAiId, formData.getAfdApprovalId()));
                record.setApprovalCatalogId(approvalInfo.getAiCtalogId());
                record.setApprovalFormDataId(formDataId);
                record.setApprovalFormDefId(formData.getAfdFormId());
                record.setApprovalInfoId(approvalInfo.getAiId());
                record.setApprovalInfoName(approvalInfo.getAiName());
                record.setApprovalOrgId(formData.getAfdOrgId());
                record.setApprovalTime(formData.getAfdTime());
                record.setApprovalInfoName(formData.getAfdOrgName());
                record.setName(formData.getAfdTitle());
                record.setApprovalUserId(formData.getAfdUserId());
                record.setApprovalUserName(formData.getAfdUserName());
                record.setProcessInstanceId(taskEntity.getProcessInstanceId());
                record.setStatus(processStatus1);
                messageProduct.sendProcessCompleteMsg(record);
            }
        } catch (Exception e) {
            log.info("流程审核完成但是发送消息异常", e);
        }

        System.out.println(processStatus1);
    }


    /**
     * 该isFailOnException()方法确定onEvent(..)方法在调度事件时抛出异常时的行为。
     * 当false返回，异常被忽略。当true返回，异常不会被忽略
     *
     * @return
     */
    @Override
    public boolean isFailOnException() {
        return true;
    }

    /**
     * 该isFireOnTransactionLifecycleEvent()方法确定此事件侦听器是在事件发生时立即触发,还是由getOnTransaction()方法确定的事务生命周期事件触发。
     * 支持的事务生命周期事件的值是：COMMITTED，ROLLED_BACK，COMMITTING，ROLLINGBACK。
     *
     * @return
     */
    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}